//
//  ZYCUpdateDutyRecordCell.m
//  ZDSC
//
//  Created by ZDTX on 2021/9/27.
//

#import "ZYCUpdateDutyRecordCell.h"
#import "ZYCAddPhotoView.h"
#import "ZYCDutyBulletionRecordDetailModel.h"

#define maxContent 200
#define BTImageTotalNumber 9
#define ZYCContentPlaceholder @"请输入内容~"
#define ZYCContentPlaceholderColor [UIColor colorWithHexString:@"#BBBBBB" alpha:1.0]


@interface ZYCUpdateDutyRecordCell ()<UITextViewDelegate,ZYCAddPhotoViewDelegate>

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextView *contentTextView;
@property (nonatomic, strong) UILabel *line;
@property (nonatomic, strong) UIButton *saveButton;
@property (nonatomic, strong) ZYCAddPhotoView *imagePickView;
@property (nonatomic, assign) NSUInteger updateImageCount;
@property (nonatomic, strong) NSMutableArray *updateImageResults;



@end
@implementation ZYCUpdateDutyRecordCell

- (void)setModel:(ZYCBusRecordReportsModel *)model{
    _model = model;
    _titleLabel.text = model.quotaName;
    if (model.appContent.length == 0) {
        _contentTextView.text = ZYCContentPlaceholder;
        _contentTextView.textColor = ZYCContentPlaceholderColor;
    }else{
        _contentTextView.text = model.appContent;
        _contentTextView.textColor = HEX_RGB(@"#2B302D");
    }
    if ([model.complete isEqualToString:@"0"]) {
        [_saveButton setTitle:@"保存" forState:UIControlStateNormal];
    }else{
        [_saveButton setTitle:@"保存成功" forState:UIControlStateNormal];
    }
    self.imagePickView.dataArray = model.busFileList.mutableCopy;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self.contentView addSubview:self.titleLabel];
        [self.contentView addSubview:self.saveButton];
        [self.contentView addSubview:self.line];
        [self.contentView addSubview:self.contentTextView];
        [self.contentView addSubview:self.imagePickView];
        
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self.contentView).offset(15.0f);
        }];
        
        [self.saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.titleLabel);
            make.right.equalTo(self.contentView).offset(-15.0f);
        }];
        
        [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.contentView);
            make.top.equalTo(self.contentView).offset(47.0f);
            make.height.mas_equalTo(1.0f);
        }];
    
        [self.contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.line.mas_bottom).offset(25.0f);
            make.left.equalTo(self.contentView).offset(15.0f);
            make.right.equalTo(self.contentView).offset(-15.0f);
            make.height.mas_equalTo(100.0f);
        }];
        
        [self.imagePickView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentTextView.mas_bottom).offset(10.0f);
            make.left.equalTo(self.contentView).offset(15.0f);
            make.right.equalTo(self.contentView).offset(-15.0f);
            make.bottom.equalTo(self.contentView).offset(-15.0f);
            make.height.mas_equalTo(100.0f);
        }];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
        
    }
    return self;
}

//时时监听
- (void)textChanged:(NSNotification*)noti{

    self.model.complete = @"0";
    [self.saveButton setTitle:@"保存" forState:UIControlStateNormal];
  //限制输入字数
    [self textViewMaxTextCount:self.contentTextView AndMaxCount:maxContent];
}

/// UITextView字数限制
/// @param textView textView
/// @param maxCount 限制字数
- (void)textViewMaxTextCount:(UITextView *)textView AndMaxCount:(int)maxCount{
    NSString *toBeString =textView.text;
    NSString *lang = [[UIApplication sharedApplication] textInputMode].primaryLanguage;
    if ([lang isEqualToString:@"zh-Hans"]) { // 中文输入
        UITextRange *selectedRange = [textView markedTextRange];
        // 获取高亮部分
        UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
        if (!position) {// 没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if (toBeString.length > maxCount) {
                textView.text = [toBeString substringToIndex:maxCount];
                [MrjToast makeToast:@"字数不能超过200字" makeView:[UIApplication sharedApplication].keyWindow];
            }
        }else{//有高亮选择的字符串，则暂不对文字进行统计和限制
            
        }
    }else{//中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (toBeString.length > maxCount) {
            textView.text = [toBeString substringToIndex:maxCount];
            [MrjToast makeToast:@"字数不能超过200字" makeView:[UIApplication sharedApplication].keyWindow];
        }
    }
}

#pragma mark - UITextViewDelegate
-(void) textViewDidEndEditing:(UITextView *)textView{
    if (textView.text.length < 1) {
        textView.text = ZYCContentPlaceholder;
        textView.textColor = ZYCContentPlaceholderColor;
        self.model.appContent = @"";
    }else{
        self.model.appContent = textView.text;
    }

}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:ZYCContentPlaceholder]) {
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
}


#pragma mark - getters
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [UILabel LabelWithFont:kSystemBoldFont(17) titleColor:HEX_RGB(kTitleThemeColor) textAlignment:ZZTextAlignmentLeft];
    }
    return _titleLabel;
}

- (UIButton *)saveButton {
    if (!_saveButton) {
        _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_saveButton setTitleColor:HEX_RGB(@"#2079D3") forState:UIControlStateNormal];
        _saveButton.titleLabel.font = kCustomFont(@"PingFangSC-Light", 17.0f);
        [_saveButton addTarget:self action:@selector(clickSaveAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveButton;
}
- (UILabel *)line {
    if (!_line) {
        _line = [[UILabel alloc] init];
        _line.backgroundColor = HEX_RGB(@"#EAEAEA");
    }
    return _line;
}

- (UITextView *)contentTextView {
    if (!_contentTextView) {
        _contentTextView = [[UITextView alloc] init];
        _contentTextView.delegate = self;
        _contentTextView.font = kCustomFont(@"PingFangSC-Regular", 16.0f);
        _contentTextView.text = ZYCContentPlaceholder;
        _contentTextView.textColor = ZYCContentPlaceholderColor;
        _contentTextView.scrollEnabled = YES;
    }
    return _contentTextView;
}


- (ZYCAddPhotoView *)imagePickView {
    if (!_imagePickView) {
        _imagePickView = [[ZYCAddPhotoView alloc] init];
        _imagePickView.delegate = self;
    }
    return _imagePickView;
}


- (void)clickSaveAction:(UIButton *)sender{
//    if (self.imagePickView.dataArray.count == 0) return;
    self.updateImageCount = 0;
    self.updateImageResults = [NSMutableArray arrayWithCapacity:0];
    for (NSObject *object in self.imagePickView.dataArray) {
        if ([object isKindOfClass:[UIImage class]]) {
            self.updateImageCount ++;
            UIImage * image = (UIImage *)object;
            [self uploadWithImage:image];
        }else{
            ZYCBusFileListModel *model = (ZYCBusFileListModel *)object;
            [self.updateImageResults addObject:model];

        }
    }
    
    [self modifyDutyRecord];

}


// 修改值班报告
- (void)modifyDutyRecord{
//    if (self.updateImageCount != 0) {
//        return;
//    }
    if (self.model.appContent.length == 0 && self.updateImageResults.count == 0) {
        [MrjToast makeToast:@"请输入内容" makeView:self.viewController.view];
        return;
    }
    NSMutableDictionary * parameter = [NSMutableDictionary dictionaryWithCapacity:0];
    [parameter setObject:self.model.recordReportId forKey:@"recordReportId"];
    [parameter setObject:self.model.quotaId forKey:@"quotaId"];
    [parameter setObject:self.model.quotaName forKey:@"quotaName"];
    [parameter setObject:self.model.appContent ? self.model.appContent : @"" forKey:@"appContent"];

    [parameter setObject:self.model.complete forKey:@"complete"];
    NSMutableArray *temp = [NSMutableArray arrayWithCapacity:0];

    if (self.updateImageResults.count > 0) {
        NSMutableString *stringM = [NSMutableString string];
        for (ZYCBusFileListModel *model in self.updateImageResults) {
            NSString *fullUrlString =  [NSString stringWithFormat:@"%@/zd-system-service%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],model.filePath];
        [stringM appendString:[NSString stringWithFormat:@"<p><img src=%@></p>",fullUrlString]];
        };
        self.model.content = [NSString stringWithFormat:@"<p>%@</p>%@",self.model.appContent,stringM];
    }
    
    [parameter setObject:self.model.content forKey:@"content"];
    for (ZYCBusFileListModel *model in self.updateImageResults) {
        NSDictionary *dict = [model yy_modelToJSONObject];
        [temp addObject:dict];
    }
    [parameter setObject:temp forKey:@"busFileList"];

    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_EditReport requestService:RequestServiceWorkBench parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(id  _Nullable responseObject) {
        [MrjSVProgressHUD dismiss];
        if (SUCCESS(responseObject[@"code"])) {
            self.model.complete = @"1";
//            self.model.busFileList = self.updateImageResults.copy;
            [self.saveButton setTitle:@"保存成功" forState:UIControlStateNormal];
            if (self.refreshBlock) {
                self.refreshBlock();
            }

        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
    
}
- (void)uploadWithImage:(UIImage *)image{
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],Common_Post_Upload];
    [[URLManager sharedURLManager] POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSString *fileName;
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"MMddHHmmss";
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        fileName = [NSString stringWithFormat:@"%@.png",dateString];//以这种格式防止上传的图片重复覆盖
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                self.updateImageCount --;
                ZYCBusFileListModel *file = [[ZYCBusFileListModel alloc] init];
                file.filePath = responseObject[@"body"][@"url"];
                file.fileName = responseObject[@"body"][@"fileName"];
                file.fileType = @"img";
                file.moduleName = @"duty_plan_record";
                file.parentId = self.model.recordReportId;
                [self.updateImageResults addObject:file];

                
                [self modifyDutyRecord];
            }else{
        
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
}

#pragma mark - ZYCAddPhotoViewDelegate

- (void)addPhotosViewDidClickDelete:(NSObject *)object{
    self.model.complete = @"0";
    [self.saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [self.imagePickView.dataArray removeObject:object];
    
    if ([object isKindOfClass:[ZYCBusFileListModel class]] ) {
        ZYCBusFileListModel * model = (ZYCBusFileListModel *)object;
//        [self.model.busFileList removeObject:model];
    }else{
        UIImage * image = (UIImage *)object;
        [self.imagePickView.dataArray removeObject:image];
    }

}

- (void)addPhotosViewUpdateSaveStatus{
    self.model.complete = @"0";
    [self.saveButton setTitle:@"保存" forState:UIControlStateNormal];
}



@end
